<?php

namespace app\admin\controller\oauth;


use app\common\controller\Backend;

class Config extends Backend
{

    protected static string $configFile = 'oauth.php';

    public function initialize(): void
    {
        parent::initialize();
    }

    public function index(): void
    {
        // 获取所有配置项
        $config = config('oauth');
        $this->success('', [
            'config' => $config,
        ]);
    }

    public function saveConfig(): void
    {
        $name = $this->request->get('name', '');
        $data = $this->request->post();
        if (!$name) {
            $this->error(__('Parameter error'));
        }

        $config        = config('oauth');
        $configPath    = config_path() . self::$configFile;
        $configContent = @file_get_contents($configPath);

        if (!isset($config[$name]) || !is_array($config[$name])) {
            $this->error(__('Parameter error'));
        }
        foreach ($config[$name] as $key => $item) {
            $item          = str_replace('/', '\/', $item);
            $configContent = preg_replace("/'$key'(\s+)=>(\s+)'$item',#$name#/", "'$key'\$1=>\$2'{$data[$key]}',#$name#", $configContent);
        }

        $result = @file_put_contents($configPath, $configContent);
        if (!$result) {
            $this->error(__('Configuration write failed: %s', ['config/' . self::$configFile]));
        }
        $this->success();
    }

}